﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace VK.Comm.Xml
{
    /// <summary>
    /// 业务对象与Xml文件的相互转换
    /// </summary>
    /// <typeparam name="T">业务对象</typeparam>
    public static class XmlFileOperate<T> where T : class
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static bool XmlFileEncode(T obj, string path)
        {
            bool success = false;

            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(fs, obj);
                success = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return success;

        }

        /// <summary>  
        /// 反序列化
        /// </summary>  
        /// <param name="obj"></param>  
        /// <param name="filename">文件路径</param>
        /// <returns></returns>  
        public static T XmlFileDecode(string path)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static string XmlEncode(T obj)
        {
            XmlSerializer xmls = new XmlSerializer(typeof(T));
            StringWriter sw = new StringWriter();
            xmls.Serialize(sw, obj);
            return sw.ToString();
        }

        /// <summary>  
        /// 反序列化
        /// </summary>  
        /// <param name="obj"></param>  
        /// <param name="filename">文件路径</param>
        /// <returns></returns>  
        public static T XmlDecode(string xml)
        {
            TextReader reader = new StringReader(xml);
            XmlSerializer xmls = new XmlSerializer(typeof(T));
            return xmls.Deserialize(reader) as T;
        }
    }
}
